package org.ljy.testdemo.interceptor;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
//把对象交给Spring管理，否则不生效
//@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取session
        HttpSession session = request.getSession(false);
        //2.判断是否存在session或者用户已登录
        if(session != null && session.getAttribute("user") != null) {
            //进入该方法，说明用户已登录，就不进行拦截操作、
            return true;
        }
        //log.info("未登录");
        //3.走到这一步，说明用户未登录，进行拦截（也可以指定跳转某一个页面）
        //response.sendRedirect("/login.html");//设置跳转的页面，一般为登陆页面
        return false;//拦截并跳转
    }
}
